package com.yutian.example.demo.web.config;

import com.yutian.example.demo.common.exceptions.MyServiceException;
import com.yutian.example.demo.common.vo.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletResponse;

/**
 * https://blog.csdn.net/jwf111/article/details/88571067
 * https://my.oschina.net/angerbaby/blog/595367
 */
@ControllerAdvice
@Slf4j
public class ErrorHandler {
    @ExceptionHandler(Exception.class)
    public ModelAndView onError(HttpServletResponse resp, Exception ex) throws Throwable {
        HttpResponse response = null;
        if(ex instanceof MyServiceException){
            MyServiceException e = (MyServiceException)ex;
            String errInfo = e.getMessage();
            if(null == e.getCause()){
                // 说明没有传递将异常堆栈，即已经打印过异常堆栈
                log.error("handle errInfo: {}, err: {}", errInfo, ex.getMessage());
            }else{
                log.error("handle errInfo: {}, err:", errInfo, ex);
            }
            response = HttpResponse.createFail(e.getCode(), errInfo);
        } else {
            log.error("handle err:", ex);
            response = HttpResponse.createFail("internal.error");
        }
        return new ModelAndView(new MappingJackson2JsonView(), response.toMap());
    }
}